<template>

    <div class="table-editor">
        <div class="form-top">
            <div class="form-tool"> 
              <div class="form-tool-btn">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRow">添加行</el-button>
                <el-button type="waring"  icon="el-icon-minus" size="mini" @click="delRow">删除行</el-button>
                <excel-upload @onSuccess="uploadExcel" size="mini" class="upload-btn">导入</excel-upload>
                <el-button style="margin-left:10px;"  icon="el-icon-notebook-2" size="mini" @click="tapTemp" v-if="showTemp">使用模板</el-button>
              </div>
            </div>
          </div>
          
        <el-table  @current-change="changeCurrentRow" :data="list" border fit highlight-current-row style="width: 100%" @row-click="tapRow">
          <el-table-column
            type="index"
            width="50"
            label="序号">
          </el-table-column>

          <el-table-column v-for="(item,tableIndex) in tableData" :key="item.field" :width="item.width" :min-width="item.minWidth" align="center" :label="item.label">
            <template slot-scope="{row}">
              <template v-if="item.type == 'look'">
                {{row[item.field]}}
              </template>
              <template v-if="item.type =='text'">
                <el-input v-if="row.edit === true"  v-model="row[item.field]" class="edit-input" :size="item.size ? item.size:'mini'"    />
                <span v-else>{{ row[item.field] }}</span>
              </template>
              <template v-if="item.type =='number'">
                <el-input-number v-if="row.edit === true"  v-model="row[item.field]" :size="item.size ? item.size:'mini'" :precision="item.precision ? item.precision : 0" :step="item.step ? item.step : 1" :min="item.min ? item.min : 0" :max="item.max ? item.max : 999999999" class="edit-input input-number"></el-input-number>
                <span v-else>{{ row[item.field] }}</span>
              </template>
              <template v-if="item.type =='price'">
                <el-input-number v-if="row.edit === true" :controls="false"  v-model="row[item.field]" :size="item.size ? item.size:'mini'" :precision="item.precision ? item.precision : 2" :step="item.step ? item.step : 1" :min="item.min ? item.min : 0" :max="item.max ? item.max : 999999999" class="edit-input input-number"></el-input-number>
                <span v-else>{{ row[item.field] }}</span>
              </template>
              <template v-if="item.type =='select'">
                <el-select v-if="row.edit === true" v-model="row[item.field]" :size="item.size ? item.size:'mini'"  clearable>
                  <el-option
                    v-for="options in item.options"
                    :key="options.value"
                    :label="options.label"
                    :value="options.value">
                  </el-option>
                </el-select>
                <span v-else>{{(row[item.field] || row[item.field] == '0')  ?  item.optionsValue[row[item.field]] : ''}}</span>
              </template>
              <!--读取数据下拉选择框-->
              <template v-if="item.type=='selectdata'">
                <el-select v-if="row.edit === true"  v-model="row[item.field]" :size="item.size ? item.size:'mini'"  :placeholder="item.placeholder" :filterable="item.filterable ? true : false" :disabled="item.readonly ? true : false"  clearable>
                  <template v-for="group in item.options">
                    <el-option-group
                      v-if="item.children && item.children.length > 0"
                      :key="group.value"
                      :label="group.label">
                        <el-option
                          v-for="item in group.children"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-option-group>
                      <el-option
                        v-else
                        :key="group.value"
                        :label="group.label"
                        :value="group.value">
                      </el-option>
                    </template>
                </el-select>
                <span v-else>{{(row[item.field] || row[item.field] == '0')  ?  item.optionsValue[row[item.field]] : ''}}</span>
              </template>
              <!--单张封面图片选择-->
              <template v-if="item.type == 'cover'">
                <el-upload
                  class="cover-uploader"
                  name="uploadFileData"
                  :data="uploadPlatformData"
                  :action="$config.uploadImgUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="(e)=>uploadCoverSuccess(e,row,item.field)">
                    <img v-if="row[item.field]" :src="row[item.field]" class="cover">
                    <i v-else class="el-icon-plus cover-uploader-icon"></i>
                </el-upload>
              </template>
              <template v-if="item.type =='selectcreate'">
                <el-select v-if="row.edit === true" v-model="row[item.field]" multiple
                filterable
                allow-create
                default-first-option
                clearable
                :placeholder="item.placeholder ? item.placeholder : ''">
                  <el-option
                    v-for="options in item.options"
                    :key="options.value"
                    :label="options.label"
                    :value="options.value">
                  </el-option>
                </el-select>
                <span v-else>{{item.options[row[item.field]] ? item.options[row[item.field]].label : ''}}</span>
              </template>
              <!--弹出表格数据列表选择框-->
              <template v-if="item.type == 'combobox'">
                <div class="combobox-wrapper">
                  <el-select
                    :size="item.size ? item.size:'mini'"
                    v-if="row.edit === true"
                    v-model="row[item.field]" @change="(e)=>changeComboboxVal(row,item,e)" :placeholder="item.placeholder" :filterable="true" :disabled="item.readonly ? true : false" class="combobox-input" clearable
                    remote
                    reserve-keyword
                    :remote-method="(e)=>remoteMethod(row,item,e)"
                    :loading="row.comboboxLoading">
                    <el-option
                      v-for="group in row.options"
                      :key="item.optionsValueField ? group[item.optionsValueField] : group.value"
                      :label="item.optionsLabelField ? group[item.optionsLabelField] : group.label"
                      :value="item.optionsValueField ? group[item.optionsValueField] : group.value">
                        <span style="float: left">{{ item.optionsLabelField ? group[item.optionsLabelField] : group.label }}</span>
                        <span style="float: right; color: #8492a6; font-size: 12px">{{ item.optionsRemarkField ? group[item.optionsRemarkField] : group.remark }}</span>
                    </el-option>
                  </el-select>
                  <span v-else>{{ row[item.field + '_combobox_label'] }}</span>
                  <div  v-if="row.edit === true" :class="item.size ? 'combobox-btn-'+item.size : 'combobox-btn-mini'" @click="tapComboboxPicker(row,item,tableIndex)">
                    <i class="el-icon-notebook-2" />
                  </div>
                </div>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <dialogDataPicker :ref="'dataPicker'+item.field" :key="item.field" v-for="item in dataPickers" @pickData="(e)=>pickComboboxData(item,e)" :multiple="item.isMultiple" :pageName="item.comboboxPage"></dialogDataPicker>
      </div>
</template>
<style scoped>
  .user-form{padding:0 0 20px;}
  .form-tool{height:40px;display: flex;}
  .form-tool-btn{display: inline;}
  .upload-btn{margin-left:10px;}
  .form-top{display: flex;align-items: center;justify-content: space-between;padding:10px 0;}
  .form-title{font-weight: bold;padding-bottom:10px;}
  .input-number{width:120px;}
  .cover-uploader{width:65px;height:65px;}
  .cover-uploader .cover-uploader-icon{width:60px;height:60px;line-height: 60px;}
  .cover{width:40px;height:40px;}
  .combobox-wrapper{display: flex;align-items: center;justify-content: center;}
  .combobox-btn-mini{height:28px;width:28px;cursor: pointer; display: flex;align-items: center;justify-content: center;position: relative;left:-2px;font-size:14px;border:1px solid #ccc;border-radius: 0 4px 4px 0;}
</style>
<script>
import excelUpload from '@/components/common/excelUpload';
import dialogDataPicker from '@/components/common/dialogDataPicker';
import {getSelectData,getTreeData,getComboboxData } from '@/api/common.js';
import {isArray} from '@/utils';
export default {
  name:'danFormTableEditor',
  props:{
    tableField:{
      type:Array,
      default(){
        return []
      }
    },
    showTemp:{
      type:Boolean,
      default(){
        return false;
      }
    }
  },
  components:{
    excelUpload,dialogDataPicker
  },
  mounted(){

  },
  created(){

  },
  data(){
    return {
      uploadHeaders:this.$store.getters.userInfo.user_token ? {'User-Token' :this.$store.getters.userInfo.user_token} : {},
      uploadPlatformData:{
        platform_app_id:this.$store.getters.appInfo.platform_app_id,
        platform_user_id:this.$store.getters.appInfo.platform_user_id,
        platform_app_user_id:this.$store.getters.appInfo.platform_app_user_id
      },
      currentRow:'',
      tableData:[],
      list:[],
      dataPickers:[],
      pickColIndex:-1,//点击了选择弹窗按钮才会更新
      comboboxItem:''
    }
  },
  methods:{
    getPickRowIndex(){
      for (let i=0; i < this.list.length; i++) {
        if (this.list[i].edit) return i;
      }
    },
    pickComboboxData(tableField,data){
      let editRowIndex = this.getPickRowIndex();
      let rowValueField = this.tableData[this.pickColIndex].comboboxGetField[0][0];
      let rowLabelField = this.tableData[this.pickColIndex].comboboxGetField[1][0];
      let getValueField = this.tableData[this.pickColIndex].comboboxGetField[0][1] ? this.tableData[this.pickColIndex].comboboxGetField[0][1] : rowValueField;
      let getLabelField = this.tableData[this.pickColIndex].comboboxGetField[1][1] ? this.tableData[this.pickColIndex].comboboxGetField[1][1] : rowLabelField;
      if (tableField.isMultiple) {
        let pickIndex = 0;
        data.forEach(item=>{
          let findIndex = this.list.findIndex(findItem=>findItem[rowValueField] == item[getValueField]);
          if (!tableField.repeat && findIndex >= 0) return;
          let row = this.getDefaultRow();
          this.tableData[this.pickColIndex].comboboxGetField.forEach((getItem,getIndex)=>{
            let rowField,dataField;
            if (getItem.length > 1) {
              rowField = getItem[0];
              dataField = getItem[1];
            } else {
              rowField = dataField = getItem;
            }
            row[rowField] = item[dataField];
          })
          row.options = [...data];
          if (pickIndex == 0) {
            this.list.splice(editRowIndex,1,row);
          } else {
            this.list.splice(editRowIndex + pickIndex,0,row);
          }
          pickIndex++;
          this.list.forEach(row=>{
            row.edit = false;
          });
        });
      } else {
        data.forEach(item=>{
          if (!tableField.repeat) {
            let findIndex = this.list.findIndex(findItem=>{
              return findItem[rowValueField] == item[getValueField] && !findItem.edit
            });
            if (findIndex >= 0) return this.$tool.toast('第'+(findIndex+1)+'行已存在该条内容，不可重复选择');
          }
          this.tableData[this.pickColIndex].comboboxGetField.forEach((getItem,getIndex)=>{
              let rowField,dataField;
              if (getItem.length > 1) {
                rowField = getItem[0];
                dataField = getItem[1];
              } else {
                rowField = dataField = getItem;
              }
              this.list[editRowIndex][rowField] = item[dataField];
          })
          this.list[editRowIndex].options = [...data];
        });
      }
      
    },
    tapComboboxPicker(row,tableField,colIndex){
      let rowValueField = tableField.comboboxGetField[0][0];
      if (tableField.multiple) {
        if (row[rowValueField] || row[rowValueField] == '0') {
          tableField.isMultiple = false;
        } else {
          tableField.isMultiple = true;
        }
      } else {
        tableField.isMultiple = false;
      }
      this.$forceUpdate();
      this.pickColIndex = colIndex;
      this.$refs['dataPicker'+tableField.field][0].open();
    },
    changeComboboxVal(row,tableField,newVal){
      if (newVal == '') {
        tableField.comboboxGetField.forEach((getItem,getIndex)=>{
          let rowField,dataField;
          if (getItem.length > 1) {
            rowField = getItem[0];
            dataField = getItem[1];
          } else {
            rowField = dataField = getItem;
          }
          row[rowField] = '';
        })
        row.options = [];
        return;
      }
      tableField.comboboxGetField.forEach((getItem,getIndex)=>{
        let rowField,dataField;
        if (getItem.length > 1) {
            rowField = getItem[0];
            dataField = getItem[1];
          } else {
            rowField = dataField = getItem;
          }
        if (row.valueObject[newVal] || row.valueObject[newVal] == '0') {
          //row[comboboxItem[0]] = row.valueObject[newVal][comboboxItem[0]];
          row[rowField] = row.valueObject[newVal][dataField];
          //this.$set(row,tableField,row.valueObject[newVal][tableField]); 
        }
      })
      
    },
    init(data = []){
      let tableData = {...this.tableField};
      this.dataPickers = [];
      for (let k in tableData) {
        //设置预设选项
        if (tableData[k].optionsType == 'sex') {
          tableData[k].options = [{label:'男',value:1},{label:'女',value:2}];
        } else if (tableData[k].optionsType == 'education'){
          tableData[k].options = [{label:'小学',value:'小学'},{label:'初中',value:'初中'},{label:'高中',value:'高中'},{label:'大专',value:'大专'},{label:'本科',value:'本科'},{label:'硕士',value:'硕士'},{label:'博士及以上',value:'博士及以上'}]
        } else if (tableData[k].optionsType == 'relation'){
          tableData[k].options = [{label:'父母',value:'父母'},{label:'子女',value:'子女'},{label:'配偶',value:'配偶'},{label:'兄弟姐妹',value:'兄弟姐妹'},{label:'其他',value:'其他'}];
        } else if (tableData[k].optionsType == 'marital'){
          tableData[k].options = [{label:'未婚',value:'未婚'},{label:'已婚',value:'已婚'},{label:'离婚',value:'离婚'},{label:'再婚',value:'再婚'},{label:'丧偶',value:'丧偶'}];
        } else if (tableData[k].optionsType == 'reward'){
          tableData[k].options = [{value:1,label:'积分'},{value:2,label:'钱包余额'},{value:8,label:'普通商品'}];
        }
        if (tableData[k].type == 'select') {
          tableData[k].optionsValue = {};
          tableData[k].options.forEach(item=>{
            tableData[k].optionsValue[item.value] = item.label;
          })
          
        } else if (tableData[k].type == 'selectdata') {
          this.getSelectData(tableData[k]);
        } else if (tableData[k].type == 'combobox'){
          this.dataPickers.push(tableData[k]);
        }
      }
      this.tableData = tableData;
      this.list = [];
    },
    changeCurrentRow(oldRow,newRow){
      
    },
    getSelectData(item){
      //获取下拉选择数据的数据源
      if (item.dataController) {
        getSelectData(item.dataController).then(data=>{
          for (let k in this.tableData) {
            if (this.tableData[k].field == item.field) {
              this.$set(this.tableData[k],'options',data);
              this.tableData[k].optionsValue = {};
              this.tableData[k].options.forEach(item=>{
                this.tableData[k].optionsValue[item.value] = item.label;
              })
              break;
            }
          }
          
        });
      }
    },
    remoteMethod(row,item,query) {

      if (query.trim() !== '') {
        this.$set(row,'comboboxLoading',true);
        setTimeout(() => {
          getComboboxData(item.dataController,{keyword:query.trim(),field:item.comboboxShowField ? item.comboboxShowField : ''}).then(data=>{
            let valueObject = {};
            data.forEach(item=>{
              valueObject[item.id] = item;
            })
            row.valueObject = valueObject;
            this.$set(row,'comboboxLoading',false);
            this.$set(row,'options',data);
          }).catch(()=>{
            this.$set(row,'comboboxLoading',false);
          })
          
        }, 150);
      } else {
        item.options = [];
      }
    },
    uploadCoverSuccess(e,row,field){
      row[field] = e.data.url;
    },
    uploadExcel({header,excelData}){
      this.list = [];
      let list = [];
      let fieldArr = [];
      excelData.forEach(data=>{
        let colmunData = {};
        this.tableField.forEach(fieldArr=>{
          for (let key in data) {
            if (fieldArr.label == key) colmunData[fieldArr.field] = data[key];
          }
        });
        list.push(colmunData);
      });
      this.list = list;
    },
    getDefaultRow(){
      let data = {};
      for (let k in this.tableData) {
        data[this.tableData[k].field] = '';
      }
      return data;
    },
    addRow(){
      this.list.forEach(row=>{
        row.edit = false;
      });
      let rowData = this.getDefaultRow();
      rowData.edit = true;
      this.list.push(rowData);
    },
    delRow(){
      let findRow = this.list.findIndex(row => row.edit );
      if (findRow > -1) this.list.splice(findRow,1);
      
    },
    tapRow(row,colmun,e){
      this.list.forEach(item=>{
        item.edit =false;
      })
      row.edit = true;
    },
    getFormData(){
      return this.list;
    },
    updateForm(data){
      this.list = data;
    },
    tapTemp(){
      this.$emit('tapTemp');
    }
  }
}
</script>